<template>
	<slot>
		<div class="user-container">
			<div class="user-box" v-show="userDataList.data.length < 1 || (limit > 1 && userDataList.data.length < limit)">
				<div class="user-empty cursor-pointer" @click="openDialog()" v-if="!disabled">
					<SvgIcon name="ele-Plus" size="15" class="avatar-user-icon" />
					<div>选择用户</div>
				</div>
				<div class="goods-empty cursor-not-allowed" v-else>
					<SvgIcon name="ele-Remove" size="15" class="avatar-goods-icon" />
					<div>禁用</div>
				</div>
			</div>
			<div class="user-box" v-for="(item, index) in userDataList.data" :key="index">
				<el-tooltip effect="dark" placement="top">
					<template #content> ID：{{ item.id }}<br />账号：{{ item.name }}</template>
					<el-image :src="item.avatar" class="user-image" fit="contain" v-if="limit > 1 || disabled" />
					<el-image :src="item.avatar" class="user-image" fit="contain" @click="openDialog()" v-else />
				</el-tooltip>
				<div class="close-icon" @click="deleteUser(index)" v-if="!disabled">
					<SvgIcon name="ele-Close" size="12" />
				</div>
				<div class="user-name">
					{{ item.name }}
				</div>
			</div>
		</div>
		<div class="el-upload__tip user-tip-text">{{ promptText }}</div>
		<el-input v-model="selectValue" type="hidden" />
	</slot>
	<el-dialog ref="dialogRef" title="用户列表" v-model="showDialog" width="960px">
		<div>
			<el-card class="layout-search-card mb-4" shadow="never" :body-style="{ paddingBottom: '0' }">
				<el-form :model="state.queryParams" ref="queryForm" :inline="true">
					<el-form-item label="账号：">
						<el-input v-model="state.queryParams.account" placeholder="请输入账号" class="w-[200px]"> </el-input>
					</el-form-item>
					<el-form-item label="昵称：">
						<el-input v-model="state.queryParams.nickname" placeholder="请输入昵称" class="w-[200px]"> </el-input>
					</el-form-item>
					<el-form-item label="手机号：">
						<el-input v-model="state.queryParams.mobile" placeholder="请输入手机号" class="w-[200px]"> </el-input>
					</el-form-item>
					<el-form-item label="分组：" prop="role_id">
						<el-select class="!w-[200px]" placeholder="请选择分组" clearable v-model="state.queryParams.role_id">
							<el-option v-for="(item, index) in groupOptionsData" :key="index" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
					<el-form-item label="状态：">
						<el-select class="!w-[150px]" v-model="state.queryParams.disable">
							<el-option label="全部" value="" />
							<el-option label="正常" value="0" />
							<el-option label="禁用" value="1" />
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button-group>
							<el-button type="primary" icon="ele-Search" @click="searchTable"> 查询 </el-button>
							<el-button icon="ele-Refresh" @click="resetQuery" class="ml15"> 重置 </el-button>
						</el-button-group>
					</el-form-item>
				</el-form>
			</el-card>
			<el-card class="layout-table-card" shadow="never">
				<el-table ref="tableRef" :data="state.tableList" highlight-current-row v-loading="state.loading" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="55" v-if="limit > 1" />
					<el-table-column width="50" v-else>
						<template #default="{ row }">
							<el-radio v-model="selectDataList.id" :label="row.id" @input="currentClick(row)">&nbsp;</el-radio>
						</template>
					</el-table-column>
					<el-table-column prop="id" label="ID" width="60" />
					<el-table-column prop="account" label="账号" show-overflow-tooltip></el-table-column>
					<el-table-column label="头像">
						<template #default="{ row }">
							<el-image
								class="w-[30px] h-[30px] flex items-center justify-center"
								:src="row.avatar"
								preview-teleported="true"
								:preview-src-list="[row.avatar]"
								fit="contain"
							/>
						</template>
					</el-table-column>
					<el-table-column prop="nickname" label="昵称" show-overflow-tooltip></el-table-column>
					<el-table-column prop="group_name" label="分组" show-overflow-tooltip></el-table-column>
					<el-table-column prop="status" label="状态" show-overflow-tooltip>
						<template #default="{ row }">
							<el-tag type="danger" v-if="row.status == 0">{{ row.status_desc }}</el-tag>
							<el-tag type="success" v-else>{{ row.status_desc }}</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="create_time" label="创建时间" show-overflow-tooltip></el-table-column>
				</el-table>
				<div class="flex justify-end mt-4">
					<pagination v-model="state" @tableChange="getTableList" />
				</div>
			</el-card>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="showDialog = false">取消</el-button>
				<el-button type="primary" @click="confirm">确认</el-button>
			</span>
		</template>
	</el-dialog>
</template>
<script lang="ts" setup>
import { ref, computed, reactive, onMounted } from 'vue';
import { userLists } from '/@/api/user/user';
import { usePage } from '/@/hooks/usePage';
import { groupAll } from '/@/api/user/group';
import user_avator from '/@/assets/user_avator.png';

const props = defineProps({
	modelValue: {
		type: String,
		required: true,
		default: '',
	},
	// 用户数量
	limit: {
		default: 1,
		required: false,
		type: Number,
	},
	// 是否禁用
	disabled: {
		type: Boolean,
		required: false,
		default: false,
	},
	// 提示文字
	promptText: {
		type: String,
		required: false,
		default: '',
	},
	// 默认信息
	defaultValue: {
		type: Array,
		required: false,
		default: [],
	},
});

const dialogRef = ref(null);

const showDialog = ref(false);

const tableRef = ref(null);

const userDataList = reactive({
	data: [],
	ids: [],
});

const selectDataList = reactive({
	data: [],
	id: 0,
});

const emit = defineEmits(['update:modelValue', 'confirm']);

const selectValue = computed({
	get() {
		return props.modelValue;
	},
	set(value) {
		emit('update:modelValue', value);
	},
});

const groupOptionsData = ref([]);

const setOptionsData = async () => {
	groupOptionsData.value = await groupAll();
};

// 定义列表
const state = reactive<TableDataState>({
	loading: false,
	tableList: [],
	queryParams: {
		account: '',
		nickname: '',
		mobile: '',
		status: '',
		group_id: '',
	},
	tableParams: {
		page_num: 1,
		page_limit: 15,
		page_total: 0 as any,
	},
});

const { getTableList, searchTable, resetQuery } = usePage({ tableData: state, apiData: userLists });

const init = () => {
	selectValue.value = props.modelValue;
	userDataList.ids = props.modelValue ? String(props.modelValue).split(','):[];

	if (props.defaultValue.length > 0) {
		userDataList.data = props.defaultValue;
	} else {
		userDataList.ids.forEach((e) => {
			userDataList.data.push({ id: e, name: '', avatar: user_avator });
		});
	}
};

const openDialog = () => {
	showDialog.value = true;
	// 重置选中数据
	selectDataList.data = [];
	selectDataList.id = 0;
	tableRef.value?.clearSelection();
};

const getData = async () => {
	getTableList();
};

const deleteUser = (index) => {
	userDataList.data.splice(index, 1);
	userDataList.ids.splice(index, 1);
	selectValue.value = userDataList.ids.join(',');
};

const handleSelectionChange = (val) => {
	selectDataList.data = [];
	val.forEach((e) => {
		selectDataList.data.push({ id: e.id, name: e.account, avatar: e.avatar });
	});
};

const currentClick = (row) => {
	selectDataList.data = [{ id: row.id, name: row.account, avatar: row.avatar }];
};

const confirm = async () => {
	showDialog.value = false;

	if (props.limit <= 1) {
		userDataList.data = [{ id: selectDataList.data[0].id, name: selectDataList.data[0].name, avatar: selectDataList.data[0].avatar }];
		userDataList.ids = [selectDataList.data[0].id];
	} else {
		selectDataList.data.forEach((e) => {
			// 检测是否超过最大限制并查重
			if (userDataList.data.length < props.limit && !userDataList.ids.includes(e.id)) {
				userDataList.data.push({ id: e.id, name: e.name, avatar: e.avatar });
				userDataList.ids.push(e.id);
			}
		});
	}

	selectValue.value = userDataList.ids.join(',');
	emit('confirm', selectValue);
};

defineExpose({
	openDialog,
});

onMounted(() => {
	getData();
	setOptionsData();
});

init();
</script>
<style lang="scss" scoped>
.el-form.el-form--inline .el-form-item--default.el-form-item:last-of-type.select-btn-group {
	margin-bottom: 0 !important;
}

.el-button.active {
	background-color: var(--el-button-hover-bg-color);
	border-color: var(--el-button-hover-border-color);
	color: var(--el-button-hover-text-color);
	outline: none;
}

.layout-search-card {
	.el-form-item {
		margin-bottom: 10px;
	}

	.el-form.el-form--inline .el-form-item--default.el-form-item:last-of-type {
		margin-bottom: 10px !important;
	}
}

.user-container {
	display: flex;
	justify-content: left;
	width: 100%;
	flex-wrap: wrap;
	.user-box {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 60px;
		height: 60px;
		transition: var(--el-transition-duration-fast);
		margin-right: 10px;
		margin-bottom: 7px;

		.user-image {
			width: 100%;
			height: 100%;
			-o-object-fit: contain;
			object-fit: contain;
			box-sizing: border-box;
			position: relative;
			border-radius: 4px;
			overflow: hidden;
			border-width: 1px;
			border-color: var(--el-border-color-extra-light);
			background-color: var(--el-border-color-extra-light);
		}

		.close-icon {
			display: flex;
			position: absolute;
			top: -6px;
			right: -6px;
			width: 16px;
			height: 16px;
			background-color: rgba(0, 0, 0, 0.3019607843);
			justify-content: center;
			align-items: center;
			border-radius: 50%;
			color: #fff;
			cursor: pointer;
		}

		.user-name {
			position: absolute;
			bottom: 0;
			right: 0;
			box-sizing: border-box;
			align-items: center;
			justify-content: center;
			width: 100%;
			height: 40%;
			cursor: pointer;
			background: rgba(0, 0, 0, 0.3);
			transition: var(--el-transition-duration-fast);
			color: #fff;
			border-radius: 0.25rem;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		.user-empty {
			position: relative;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			box-sizing: border-box;
			border: 1px dashed var(--el-border-color-darker);
			width: 100%;
			height: 100%;
			border-radius: 0.25rem;
			font-size: 12px;
			color: var(--el-text-color-secondary);
		}

		.avatar-user-icon {
			margin-top: 5px;
			font-size: 25px;
			color: rgba(0, 0, 0, 0.45);
			text-align: center;
		}
	}
}

.user-tip-text {
	color: #999;
	margin-top: 0;
}
</style>
